<template>
  <div class="box_4_1 boxli">
    <div v-show="current_type=='index_recommend'" class="index_recommend">
      <div style="display: block; min-width: 500px; position: relative;">
        <a-space>
          <a-input v-model="recTitle" style="width: 100%; min-width: 300px; margin-bottom: 10px; font-size: 15px;" max-length="50" size="medium" placeholder="标题" allow-clear />
        </a-space>
        <span style="margin-left: 20px;" 
         >
            <Button 
              @click="current_type = current_type === 'index_recommend' ? 'writer_swiper' : 'index_recommend'" type="primary">
                管理轮播
            </Button>
        </span>
      </div>
      <div style="display: flex;">
          <span style="font-size: 15px;margin:0 10px 0 10px;">日期:</span>
         <div>
          <a-date-picker style="width: 220px; margin: 0 24px 24px 10px;" show-time format="YYYY-MM-DD hh:mm" @change="handleDateChange" />
        </div>
      </div>
      
      <div style="display: block;">
        <span style="font-size: 15px;margin:0 10px 0 10px;">图片:</span>
        <div style="display: inline-block;margin-bottom: 20px;">
          <a-upload list-type="picture-card" v-model="fileList" image-preview :auto-upload="false" limit="3" :multiple="true" @change="handleImageListChange" :show-retry-button="false" />
        </div>
      </div>
      <span style="font-size: 15px;margin:0 10px 0 10px;">文本:</span>
      <div>
        <div>
          <span id="txtUploadBtn"><Button @click="handleTxtUpload" style="height: 30px; line-height:30px; width: 125px;" type="success">上传</Button></span>
          <input @change="handleTxtChangeDisplay" accept=".txt" type="file" ref="txtInput" style="display: none;" />
          <span id="txtFileList" style="display: none;">
            <span>{{ txtFileName }}</span>
            <span @click="handleTxtPreview" class="iconfont icon-preview" style="vertical-align: middle; font-size: 20px;margin-left: 10px;"></span>
            <span @click="handleTxtDelete" class="iconfont icon-shanchu1" style="display: inline-block; font-size:15px;margin-left: 10px;vertical-align: middle;"></span>
          </span>
        </div>
      </div>
      <div style="display: block; margin-top: 80px;">
        <a-button style="margin-left: 50px; width: 120px;" type="primary" @click="handleDataUpload">提交</a-button>
      </div>
      <div class="index_recommend_preview">
        <br>
        <div style="border-top: 1px solid #000; width: 800px; margin: 0 auto;"></div>
        <div v-if="indexPreList != undefined">
          <div v-for="(item, index) in indexPreList" :uuid="item.id" class="listItem" :key="index">
            <span style="font-size: 15px;margin:0 10px 0 10px;">时间: {{ item.date}}</span>
            <span>标题: {{ item.title }}</span>
            <Button :uuid="item.id" @click="handleDeleteItem" style="height: 100%; margin-left: 10px;" type="error">删除</Button>
            <Button :uuid="item.id" @click="handlePreviewItem" style="height: 100%; margin-left: 10px;" type="success">预览</Button>
          </div>
        </div>
      </div>
    </div>
    
    <div v-show="current_type=='writer_swiper'" class="writer_swiper">
   
      <div >
          <p  style="text-align: center; font-weight: 800;">只支持单文件上传</p>
          <div style="display: flex; gap: 10px">
            <Button 
            @click="current_type = current_type === 'index_recommend' ? 'writer_swiper' : 'index_recommend'" type="primary">
                主页推荐
          </Button> 
              <Button type="primary" @click="swiper_file.click()">上传内容</Button>
              <Button type="primary" @click="displayArea.innerHTML='',swiper_file_value=null">清除内容</Button>
              <Button type="primary" @click="put_swiper_data">提交</Button>
            </div>
          <div class="swiper-botton">
              <div >
                
                  <input ref="swiper_file" type="file" style="display: none;" @change="deal_swiper_file_input">
              </div>
              <div ref="displayArea" style="display: flex;justify-content: center;">
                
              </div>
              
          </div>
          <div  v-if="swiper_file_value" style="border-top: 1px solid #000; width: 800px; margin: 2px auto;"></div>
          <div >
            <div v-for="(i,index) in SWIPERDATA " :key="index" 
            
            style="display: flex ;gap:200px;margin: 5px;background-color: #808695;border-radius: 5px;">
                <span>{{index}} : </span> <span>{{'时间:'+i.date}}</span>
                <span @click="delete_swiper_data(i.id)">删除</span><span @click="displayFile(i.content)" >预览</span>
          </div>


      </div>
     
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import {
  update_index_rec, delete_index_rec,
  put_writer_swiper_data, get_writer_swiper_data, delete_writer_swiper_data
} from "../../../api/admin.js";
import { get_index_recommend } from "../../../api/community/main.js";
import { success, warning } from '../../../static/js/alert.js';
const current_type = ref('index_recommend');
const swiper_file=ref(null)
let recdate=ref(new Date().toLocaleString().split(' ')[0])
let recTitle = ref();
let txtInput = ref();
let txtFile = undefined;
let fileList = ref([]);
let txtFileName = ref();
let indexPreList = ref();
const SWIPERDATA = ref([])
const SWIPERMETA = ref({})
const swiper_file_value=ref(null)
const displayArea=ref(null)
const handleDateChange = function (date_) {
   recdate.value = date_;
   console.log(recdate.value);
};

const handleImageListChange = function (filelist) {
  fileList.value = filelist;
};

const handleTxtUpload = function () {
  if (txtInput.value.files.length === 1) {
    console.log("限制文件数量");
    return;
  }
  txtInput.value.click();
};

const handleTxtChangeDisplay = function (e) {
  if (e.target.files.length > 0) {
    txtFile = txtInput.value.files[0];
    txtFileName.value = txtFile.name;
    document.querySelector('#txtFileList').style.display = 'inline-block';
    document.querySelector('#txtUploadBtn').style.display = 'none';
  } else {
    document.querySelector('#txtFileList').style.display = 'none';
    document.querySelector('#txtUploadBtn').style.display = 'inline-block';
  }
};

const handleTxtPreview = function () {
  let reader = new FileReader();
  reader.readAsText(txtFile);
  reader.onload = function (e) {
    var preBox = document.createElement('div');
    preBox.setAttribute('class', 'txtPreview');
    preBox.innerHTML = e.target.result;
    preBox.addEventListener('click', () => {
      document.querySelector('.index_recommend').removeChild(preBox);
    });
    document.querySelector('.index_recommend').append(preBox);
  };
};

const handleTxtDelete = function () {
  txtFile = undefined;
  txtInput.value.setAttribute('type', 'text');
  txtInput.value.setAttribute('type', 'file');
  document.querySelector('#txtFileList').style.display = 'none';
  document.querySelector('#txtUploadBtn').style.display = 'inline-block';
};

const handleDataUpload = async function () {
  if (!txtFile) {
    warning("强制文本上传!");
    return;
  }
  if (recTitle.value == undefined) {
    warning("请填写标题!");
    return;
  }
  let files = [];
  fileList.value.forEach((item) => {
    files.push(item.file);
  });
  files.push(txtFile);
  const judge = await update_index_rec(files, recdate.value,recTitle.value);
  if (judge == 1) {
    fileList.value = [];
  }
};

const handlePreviewItem = async function (e) {
  const id = e.target.parentNode.getAttribute("uuid");
  let recData = await get_index_recommend(3, id);
  let coverBox = document.createElement('div');
  coverBox.classList.add('txtPreviewCover');
  let box = document.createElement('div');
  box.innerHTML = `
    <p>时间: ${recData.date}</p>
    <p>标题: ${recData.title}</p>
    <p>内容: ${recData.txt}</p>
  `;
  coverBox.addEventListener('click', () => {
    document.querySelector('.index_recommend').removeChild(coverBox);
    document.querySelector('.index_recommend').removeChild(box);
  });
  box.classList.add('txtPreviewBox');
  box.addEventListener('click', () => {
    document.querySelector('.index_recommend').removeChild(coverBox);
    document.querySelector('.index_recommend').removeChild(box);
  });
  document.querySelector(".index_recommend").append(coverBox);
  document.querySelector(".index_recommend").append(box);
};

const handleDeleteItem = async function (e) {
  const id = e.target.parentNode.getAttribute("uuid");
  await delete_index_rec(id);
  const data = await get_index_recommend(1);
  if (data == undefined || data != 404 || data != 0) {
    indexPreList.value = data;
  }
};
//处理轮播管理
// 由于原先过多行内css简单写一下,使用
const fileToBase64=(file) =>{
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file); // 开始读取文件
    reader.onload = () => resolve(reader.result); // 成功时返回 Base64 字符串
    reader.onerror = error => reject(error); // 失败时返回错误
  });
}
const deal_swiper_file_input =  (e) => { 
  const file=e.target.files[0]
  if (!file) return;
  // 限制文件大小不超过 16MB（16 * 1024 * 1024 字节）
  const MAX_SIZE = 16 * 1024 * 1024; // 16MB
  if (file.size > MAX_SIZE) {
    warning("文件限制16MB")
    e.target.value = ''; // 清空文件输入
    swiper_file_value.value = null; // 清空绑定的值
    return; // 直接退出，不执行后续操作
  }
  swiper_file_value.value=null
  fileToBase64(file)
    .then(base64String => {
      swiper_file_value.value = base64String
      displayFile(base64String)
    })
    .catch(error => {
      console.error('转换失败:', error);
    });
}
const getMimeTypeFromBase64=(base64String)=> {
  const mimeType = base64String.match(/^data:(.*?);base64,/)?.[1];
  return mimeType || null; // 如果没有前缀，返回 null
}
const displayFile=(base64String)=>{
  displayArea.value.innerHTML = ''; // 清空之前的内容
  const mimeType=getMimeTypeFromBase64(base64String)

  if (mimeType.startsWith('image/')) {
    // 图片：直接显示
    const img = document.createElement('img');
    img.classList.add('swiper-show-box')
    img.src = base64String;
    img.style.maxWidth = '100%';
    displayArea.value.appendChild(img);

  } else if (mimeType.startsWith('video/')) {
    // 视频：用 <video> 播放
    const video = document.createElement('video');
    video.classList.add('swiper-show-box')
    video.src = base64String;
    video.controls = false; // 显示控制条
    video.style.maxWidth = '100%';
    video.loop=true
    video.muted = true
    video.autoplay=true
    displayArea.value.appendChild(video);



  } else if (mimeType === 'text/plain') {
    // 文本：用 <pre> 显示（保留换行和空格）
    const pureBase64 = base64String.split(',')[1] || base64String;
    const text = atob(pureBase64); // Base64 解码
    const pre = document.createElement('pre');
    pre.classList.add('swiper-show-box')
    pre.textContent = text;
    pre.style.whiteSpace = 'pre-wrap'; // 自动换行
    displayArea.value.appendChild(pre);

  } else {
    // 其他类型：提示不支持
    displayArea.value.textContent = '不支持此文件格式，仅支持图片、视频、文本';
  }
}
const put_swiper_data = async() => { 
  const judge = await put_writer_swiper_data(swiper_file_value.value)
  if (judge == 200) { 
    success("上传成功!")
  }
}
const delete_swiper_data = async (id) => {
  const judge = await delete_writer_swiper_data(id)
  if (judge == 200) { 
    SWIPERDATA.value=SWIPERDATA.value.filter((i)=>i.id!=id )
  }
}


onMounted(async () => {
    const data = await get_index_recommend(1);
    if (data == undefined || data != 404 || data != 0) {
      indexPreList.value = data;
  }
  const data2 = await get_writer_swiper_data(1)
  console.log(data2)
  if (data2 != 0) { 
      SWIPERDATA.value = data2.data
      SWIPERMETA.value = {
        total: data2.total,
        page:data2.page
      }
  }
      
  
});
</script>

<style scoped>
.index_recommend {
  padding-top: 20px;
  background-color: #f8f8f9;
  height: 800px;
}

.index_recommend > div {
  display: inline-block;
}

.index_recommend_preview {
  display: block;
  width: 1098px;
}

.listItem {
  width: 100%;
  height: 32px;
  font-size: 16px;
  line-height: 32px;
  background-color: #f8f8f9;
  border-radius: 2px;
  margin: 5px 0 5px 0;
}

::v-deep(.listItem > span) {
  display: inline-block;
  font-size: 16px;
}

::v-deep(.listItem > span:nth-child(1)) {
  width: 200px;
  margin-right: 20px;
}

::v-deep(.listItem > span:nth-child(2)) {
  width: 650px;
  margin-right: 20px;
  vertical-align: middle;
}

::v-deep(.listItem > span:nth-child(3)) {
  width: 50px;
  margin-right: 20px;
}

.index_recommend_preview > div:nth-child(3) {
  overflow: scroll;
  height: 380px;
}

.index_recommend_preview > div:nth-child(3)::-webkit-scrollbar {
  width: 12px;
}

.index_recommend_preview > div:nth-child(3)::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.index_recommend_preview > div:nth-child(3)::-webkit-scrollbar-thumb {
  width: 12px;
  background: #888;
  border-radius: 5px;
}

.index_recommend_preview > div:nth-child(3)::-webkit-scrollbar-thumb:hover {
  background-color: #555;
}

::v-deep(.txtPreview) {
  position: absolute;
  top: 120px;
  width: 450px;
  z-index: 100;
  background-color: beige;
  left: 50%;
  height: 300px;
  overflow: scroll;
  margin-left: 0px;
  border-radius: 5px;
}

::v-deep(.txtPreview)::-webkit-scrollbar {
  display: none;
}

::v-deep(.txtPreviewBox) {
  width: 1000px;
  height: 550px;
  position: absolute;
  top: 50px;
  z-index: 100;
  left: 50%;
  margin-left: -500px;
  background-color: white;
  border-radius: 5px;
}

::v-deep(.txtPreviewCover) {
  width: 100vw;
  height: 100vh;
  background-color: #f8f8f9;
  opacity: 0.5;
  z-index: 99;
  position: absolute;
  top: 0px;
  left: 0px;
}

.writer_swiper{
  padding-top: 20px;
  background-color: #f8f8f9;
  height: 800px;
  position: relative;
}
.swiper-show{
  margin-left: 50px;
  width: 300px;
  height:auto;
}
.swiper-botton{
  display: flex;
  justify-content: center;

}
::v-deep(.swiper-show-box){
  width: 500px;
  margin: 0 auto;
  max-height: 350px;
  height: 350px;
}

</style>